import http from '@/utils/request.js'
import API from '@/config/api.config'
import authService from '@/apis/auth';


Page({
  data: {
    activeTab: 0,
    countdown: 0,
    phone_number: '',
    agreementChecked: false,
  },
  // 添加新方法
  toggleAgreement() {
    this.setData({ agreementChecked: !this.data.agreementChecked });
  },
  // 切换选项卡
  changeTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    this.setData({ activeTab: tab });
  },
  // 在Page方法内添加：
  onPhoneInput(e) {
    this.setData({
      phone_number: e.detail.value
    });
  },
  //登录成功后
  loginSuccess(data) {
    wx.setStorageSync('access_token', data.access_token);
    wx.setStorageSync('refresh_token', data.refresh_token); 
    const app = getApp()
    console.log(data.user)
    app.globalData.userInfo = data.user
    wx.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 2000,
      success: () => {
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }, 2000);
      }
    }); 
  },
  // 用户名登录
  usernameLogin(e) {
    if (!this.data.agreementChecked) {
      wx.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }
    if (!e.detail.value.username) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      });
      return; 
    }
    if (!e.detail.value.password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return; 
    }
    const { username, password } = e.detail.value;
    authService.login(username, password).then(res => {
     this.loginSuccess(res.data) 
    }).catch(err => {
      wx.showToast({
        title: '登录失败',
        icon:'error',
        duration: 2000
      }); 
    });
  },
  // 获取验证码
  async getVerifyCode() {
    if (!this.data.agreementChecked) {
      wx.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }
    if (!this.data.phone_number) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      }); 
      return;
    }
    if (this.data.countdown > 0) return;
    
    // 这里添加短信发送逻辑
    const res=await authService.sendSms(this.data.phone_number)
    if (res.code == 200) {
      wx.showToast({
        title: '发送成功',
        icon:'success',
        duration: 2000
      });
      return;
    }
    this.setData({ countdown: 60 });
    const timer = setInterval(() => {
      if (this.data.countdown <= 1) {
        clearInterval(timer);
        this.setData({ countdown: 0 });
        return;
      }
      this.setData({ countdown: this.data.countdown - 1 });
    }, 1000);    
  },
  // 短信登录
  async smsLogin(e) {
    if (!this.data.agreementChecked) {
      wx.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }
    if (!this.data.phone_number) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      }); 
      return;
    }
    if (!e.detail.value.code) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      }); 
      
      return;
    }
    const { phone, code } = e.detail.value;
    try{
      // 添加验证码校验逻辑
      const res = await authService.smsLogin({ phone, code })
      this.loginSuccess(res.data)      
    }catch(err){
      wx.showToast({
        title: '登录失败',
        icon:'error',
        duration: 2000
      }); 
    }
  },

  // 微信登录
  // 获取用户信息（头像）
  getUserInfo(e) {
    if (e.detail.userInfo) {
      this.setData({
        avatarUrl: e.detail.userInfo.avatarUrl
      });
      // 这里可以上传头像到服务器
    }
  },
  // 获取手机号
  getPhoneNumber(e) {
    if (!this.data.agreementChecked) {
      wx.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const encryptedData = e.detail.encryptedData
      const iv = e.detail.iv
      // 1. 获取code
      wx.login({
        success: res => {
          // 2. 将code、encryptedData、iv发送到后端
          wx.request({
            url: http.baseUrl+'/auth/wechat/callback',
            method: 'POST',
            data: {
              code: res.code,
              encryptedData,
              iv,
              avatar: this.data.avatarUrl,
            },
            success: (res) => {
              // 3. 处理返回结果
              if (res.data.code==200) {
                this.loginSuccess(res.data)
              } else {
                // 新用户注册流程
                wx.showToast({
                  title: '用户不存在',
                  icon: 'error',
                  duration: 2000
                });
              }
            }
          })
        }
      })
    }
  },
  // 修改后的生命周期函数
  onShow() {
    const app = getApp();
    
    app.checkToken().then(valid => {
      if (valid) {
        // 已登录则跳转首页
        wx.switchTab({
          url: '/pages/index/index'
        });
      }
      // 未登录则保持当前页面
    });
  },
  onUnload() {
    const app=getApp()
    wx.setKeepScreenOn({
      keepScreenOn: app.globalData.isRecording,
      success: () => console.log('常亮已启用')
    });
  }
});
